'''
Created on Mar 24, 2013

@author: Petko
'''
from django.views.generic.base import View
from sent.utils import CommonResult, ErrorIds, createValidToken
from sent.utils.result_printer import getPrinter
from sent.model.UserDBManager import UserDBManager

class GetGroupUsers(View):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
    
    def get(self, *args, **kwargs):
        accessTokenStr = self.request.GET.get('access_token', None)
        group_id = self.request.GET.get('group_id', None)
        
        cResult = CommonResult()
        
        try:
            offset = int(self.request.GET.get('offset', 0))
            size = int(self.request.GET.get('size', 100))
        except ValueError:
            cResult.errorId = ErrorIds.BADREQUEST
            cResult.result = 'Bad format'
            return getPrinter().printResult(cResult)
        
        if accessTokenStr and group_id:
                
            accessToken, error = createValidToken(accessTokenStr, 'group_adm')
            if accessToken:
                dbMan = UserDBManager(True)
                try:
                    users, totalCount = dbMan.getGroupUsers(group_id, offset, size)
                    cResult.totalResults = totalCount
                    cResult.errorId = ErrorIds.SUCCESS
                    cResult.result = [user.toPrimitiveDict() for user in users]
                finally:
                    dbMan.closeSession()
            else:
                cResult.errorId = ErrorIds.UNAUTHORIZED
                cResult.result = error
        else:
            cResult.errorId = ErrorIds.BADREQUEST
            cResult.result = "Missing parameter"
            
        return getPrinter().printResult(cResult) 